<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关参数！"
                :closable="false"
                type="warning"
                show-icon>
      </el-alert>
      <div style="margin: 15px 0;">选择商品分类:
        <el-cascader v-model="cascadervalue"
                     :options="goodsCates"
                     :props="cascaderProps"
                     @change="cascaderHandleChange"></el-cascader>
      </div>
      <el-tabs v-model="activeName"
               @tab-click="tabsHandleClick">
        <el-tab-pane label="动态参数"
                     name="many">
          <el-button @click="addParamsDialogVisible=true"
                     :disabled="isDisabled"
                     type="primary"
                     size="mini">添加参数</el-button>
          <el-table boder
                    stripe
                    :data="manyTableData">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag @close="removeTag(scope.row),index"
                        closable
                        v-for="(item,index) in scope.row.attr_vals"
                        :key="index">{{item}}</el-tag>
                <el-input class="input-new-tag"
                          v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue"
                          ref="saveTagInput"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)"
                          @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else
                           class="button-new-tag"
                           size="small"
                           @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"
                             label="#"></el-table-column>
            <el-table-column prop="attr_name"
                             label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button @click="showEditDialog(scope.row)"
                           type="primary"
                           icon="el-icon-edit"
                           size="mini">修改</el-button>
                <el-button @click="showDelete(scope.row)"
                           type="danger"
                           icon="el-icon-delete"
                           size="mini">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性"
                     name="only">
          <el-button @click="addParamsDialogVisible=true"
                     :disabled="isDisabled"
                     type="primary"
                     size="mini">添加属性</el-button>
          <el-table boder
                    stripe
                    :data="onlyTableData">
            <el-table-column type="expand"></el-table-column>
            <el-table-column type="index"
                             label="#"></el-table-column>
            <el-table-column prop="attr_name"
                             label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button @click="showEditDialog(scope.row)"
                           type="primary"
                           icon="el-icon-edit"
                           size="mini">修改</el-button>
                <el-button @click="showDelete(scope.row)"
                           type="danger"
                           icon="el-icon-delete"
                           size="mini">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog :title="'添加'+addParamsText"
               :visible.sync="addParamsDialogVisible"
               width="50%">
      <el-form :rules="addParamsRules"
               ref="addParamsFormRef"
               :model="addParamsForm"
               label-width="80px">
        <el-form-item prop="attr_name"
                      :label="addParamsText">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="submitAddParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改属性 -->
    <el-dialog :title="'修改'+ addParamsText"
               :visible.sync="editParamsDialogVisible"
               width="50%">
      <el-form :rules="addParamsRules"
               ref="editParamsFormRef"
               :model="editParamsForm"
               label-width="80px">
        <el-form-item prop="attr_name"
                      :label="addParamsText">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="submitEditParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      goodsCates: [],
      cascadervalue: [],
      cascaderProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id'
      },
      activeName: 'many',
      manyTableData: [],
      onlyTableData: [],
      addParamsDialogVisible: false,
      addParamsForm: {
        attr_name: ''
      },
      editParamsDialogVisible: false,
      editParamsForm: {
        attr_name: ''
      },
      inputVisible: false,
      inputValue: '',
      addParamsRules: {
        attr_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ]
      }
    }
  },

  created () {
    this.getGoodsCate()
  },
  computed: {
    isDisabled () {
      return this.cascadervalue.length !== 3
    },
    cateId () {
      if (this.cascadervalue.length !== 3) {
        return null
      }
      return this.cascadervalue[2]
    },
    addParamsText () {
      return this.activeName === 'only' ? '静态属性' : '动态参数'
    }
  },

  methods: {
    async getGoodsCate () {
      const { data: res } = await this.$axios.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.goodsCates = res.data
    },
    async getParams () {
      if (this.cascadervalue.length !== 3) {
        this.cascadervalue = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      const { data: res } = await this.$axios.get('categories/' + this.cateId + '/attributes', {
        params: {
          sel: this.activeName
        }
      })
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split('')
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'only') {
        this.onlyTableData = res.data
      } else {
        this.manyTableData = res.data
      }
    },
    cascaderHandleChange () {
      this.getParams()
    },
    tabsHandleClick () {
      this.getParams()
    },
    submitAddParams () {
      this.$refs.addParamsFormRef.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.post('categories/' + this.cateId + '/attributes', {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('获取失败')
        this.getParams()
        this.$message.success('创建成功')
        this.addParamsDialogVisible = false
      })
    },
    showEditDialog (row) {
      this.editParamsDialogVisible = true
      console.log(row)
      this.editParamsForm = { ...row }
    },
    submitEditParams () {
      this.$refs.editParamsFormRef.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`, {
          attr_name: this.editParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error('更新失败')
        this.$message.success('更新成功')
        this.getParams()
        this.editParamsDialogVisible = false
      })
    },
    showDelete (row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete(`categories/${this.cateId}/attributes/${row.attr_id}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败!')
        this.$message.success('删除成功')
        this.getParams()
      }).catch(() => {
        this.$message('已取消删除')
      })
    },
    async handleInputConfirm (row) {
      if (row.inputValue.trim() === '') {
        row.inputVisible = false
        row.inputValue = ''
        return
      }
      row.attr_vals.push(row.inputValue)
      const { data: res } = await this.$axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('更新失败!')
      this.$message.success('更新成功')
      row.inputVisible = false
      row.inputValue = ''
    },
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async removeTag (row, index) {
      row.attr_vals.splice(index, 1)
      const { data: res } = await this.$axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('更新失败!')
      this.$message.success('更新成功')
    }
  }
}
</script>

<style scoped lang='less'>
.el-tag {
  margin: 7px;
}
</style>
